﻿using Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using NoticeWechat;
using System;
using System.DrawingCore.Imaging;
using System.IO;

namespace NoticeWechatApi.Controllers
{
    public class VerifyCodeController : ApiController
    {
        IMemoryCache _cache;
        public VerifyCodeController(IMemoryCache cache)
        {
            _cache = cache;
        }

        [HttpGet]
        public string NumberVerifyCode()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode);
            byte[] codeImage = VerifyCodeHelper.GetSingleObj().CreateByteByImgVerifyCode(code, 80, 40);
            var id = Guid.NewGuid().ToString("N");
            string str = $"data:image/png;base64,{codeImage.ToBase64String()}###{id}";
            _cache.Set(id, code, new  MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120) });
            return str;
        }

        [HttpGet]
        public string AbcVerifyCode()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.AbcVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            MemoryStream stream = new();
            bitmap.Save(stream, ImageFormat.Png);
            var id = Guid.NewGuid().ToString("N");
            string str = $"data:image/png;base64,{stream.ToArray().ToBase64String()}###{id}";
            _cache.Set(id, code, new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120) });
            return str;
        }

        [HttpGet]
        public string MixVerifyCode()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            MemoryStream stream = new(); 
            bitmap.Save(stream, ImageFormat.Gif);
            var id = Guid.NewGuid().ToString("N");
            string str = $"data:image/png;base64,{stream.ToArray().ToBase64String()}###{id}";
            _cache.Set(id, code, new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(120) });
            return str;
        }
    }
}
